package com.googlecode.zh.wicket.mask;


import org.apache.wicket.AttributeModifier;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.IModel;
import org.apache.wicket.util.convert.ConversionException;
import org.apache.wicket.validation.validator.StringValidator;

/**
 * Ignore punctuation chars on model
 *
 * @author golyo
 *
 */
public class MaskedTextField extends TextField<String> {

    private static final long serialVersionUID = -1306558548755385383L;
    private static final String PUNCT_REGEXP = "\\p{Punct}";
    
    private boolean checkMaskLength = false;
    private String mask;

    /**
     * Constructor
     *
     * @param id
     * @param mask
     */
    public MaskedTextField(String id, String mask) {
        this(id, null, mask);
    }

    /**
     * Constructor
     *
     * @param id
     * @param model
     * @param mask
     */
    public MaskedTextField(String id, IModel<String> model, String mask) {
        super(id, model);
        this.mask = mask;
        add(new AttributeModifier("alt", mask));
    }

    /**
     * If check mask length
     *
     * @param checkMaskLength Set if check mask length
     * @return Returns text field instance
     */
    public MaskedTextField setCheckMaskLength(boolean checkMaskLength) {
        this.checkMaskLength = checkMaskLength;
        return this;
    }

    protected String convertValue(String[] value) throws ConversionException {
        String val = super.convertValue(value);
        return val != null ? val.replaceAll(PUNCT_REGEXP, "") : null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void onInitialize() {
        super.onInitialize();
        if (checkMaskLength) {
            int length = mask.replaceAll(PUNCT_REGEXP, "").length();
            add(new StringValidator(length, length));
        }
    }
}
